package com.example.hetong_system.service;

import com.example.hetong_system.model.*;
import com.example.hetong_system.model.dto.ClauseDetailDTO;
import com.example.hetong_system.repository.ClauseRepository;
import com.example.hetong_system.repository.ContractClauseRepository;
import com.example.hetong_system.repository.ContractRepository;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ClauseService {

    @Autowired
    private ClauseRepository clauseRepository;

    @Autowired
    private ContractRepository contractRepository;

    @Autowired
    private ContractClauseRepository contractClauseRepository;

    // 创建新条款
    @Transactional
    public Clause createClause(String content) {
        // 检查content是否是JSON格式的字符串，如果是则提取实际内容
        if (content != null && content.startsWith("{") && content.endsWith("}")) {
            try {
                JSONObject jsonObject = new JSONObject(content);
                if (jsonObject.has("content")) {
                    content = jsonObject.getString("content");
                }
            } catch (JSONException e) {
                // 如果解析失败，保持原内容不变
//                log.warn("Failed to parse content as JSON: {}", content, e);
                System.out.println("解析失败");
            }
        }

        Clause clause = new Clause();
        clause.setContent(content);
        clause.setUsageCount(0);
        return clauseRepository.save(clause);
    }

    // 关联条款到合同
    @Transactional
    public void associateClauseWithContract(Long contractId, Long clauseId, String type) {
        Contract contract = contractRepository.findById(contractId)
                .orElseThrow(() -> new IllegalArgumentException("合同不存在"));

        Clause clause = clauseRepository.findById(clauseId)
                .orElseThrow(() -> new IllegalArgumentException("条款不存在"));

        // 检查是否已关联
        boolean exists = contractClauseRepository.existsByContractIdAndClauseId(contractId, clauseId);
        if (exists) {
            throw new IllegalStateException("条款已关联到合同");
        }

        // 创建关联 - 使用三参数构造函数
        ContractClause contractClause = new ContractClause(contract, clause, type);

        // 保存关联
        contractClauseRepository.save(contractClause);

        // 更新使用计数
        clause.setUsageCount(clause.getUsageCount() + 1);
        clauseRepository.save(clause);
    }

    // 获取合同的所有条款
    public List<Clause> getClausesByContractId(Long contractId) {
        return clauseRepository.findByContractClausesContractId(contractId);
    }

    // 获取未关联到合同的条款
    public Page<Clause> getUnassociatedClauses(Long contractId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return clauseRepository.findUnassociatedClauses(contractId, pageable);
    }

    // 从合同中移除条款关联
    @Transactional
    public void removeClauseFromContract(Long contractId, Long clauseId) {
        // 删除关联
        contractClauseRepository.deleteByContractIdAndClauseId(contractId, clauseId);

        // 更新使用计数
        Optional<Clause> clauseOptional = clauseRepository.findById(clauseId);
        clauseOptional.ifPresent(clause -> {
            clause.setUsageCount(clause.getUsageCount() - 1);
            clauseRepository.save(clause);
        });
    }

    // 获取条款详情，包括审核状态和意见
    @Transactional(readOnly = true)
    public ClauseDetailDTO getClauseDetail(Long contractId, Long clauseId) {
        ClauseDetailDTO dto = new ClauseDetailDTO();

        // 查询合同条款关联信息
        ContractClause contractClause = contractClauseRepository.findById(
                        new ContractClauseId(contractId, clauseId))
                .orElseThrow(() -> new IllegalArgumentException("条款不存在"));

        // 设置基本信息
        dto.setId(contractClause.getClause().getId());
        dto.setContent(contractClause.getClause().getContent());
        dto.setType(contractClause.getType());
        dto.setUsageCount(contractClause.getClause().getUsageCount());

        // 设置审核状态和意见
        dto.setLegalAuditStatus(contractClause.getLegalAuditStatus());
        dto.setLegalOpinion(contractClause.getLegalOpinion());
        dto.setFinanceAuditStatus(contractClause.getFinanceAuditStatus());
        dto.setFinanceOpinion(contractClause.getFinanceOpinion());
        dto.setCustomerAuditStatus(contractClause.getCustomerAuditStatus());
        dto.setCustomerOpinion(contractClause.getCustomerOpinion());

        return dto;
    }
}